﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Net;
using System.IO;
using Timer = System.Timers;

namespace ElektriSkeemTing
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //Muutujad
        public string server_Url = "";
        public int currentID = 0;
        public string studentName = "";
        public string testName = "";
        public string startTime = "";
        public string endTime = "";
        public bool testEnded = false;
        //Objektid
        Timer.Timer testTimer;
        XmlTextReader reader;
        Questions.Question[] questions;
        TreeNode[] gui_questions;
        

        /// <summary>
        /// Load question to test
        /// </summary>
        /// <param name="id">Question ID</param>
        private void LoadQuestion(int id)
        {
            try
            {
                if (questions[id].picUrl != "")
                {
                    try
                    {
                        lbl_Q.Visible = false;
                        img_Ting.Visible = true;
                        Stream ImageStream = new WebClient().OpenRead("http://" + server_Url + "/images/" + questions[id].picUrl);
                        img_Ting.Image = Image.FromStream(ImageStream);
                    }
                    catch (System.Net.WebException n)
                    {
                        MessageBox.Show("Serveris puudub pilt! \n" + n.Message);
                    }
                }
                else
                {
                    img_Ting.Visible = false;
                    lbl_Q.Visible = true; 
                }
                list_Q.SelectedNode = list_Q.Nodes[id];
                lbl_Progress.Text = "Nr: " + (currentID+1).ToString() + "/" + questions.Length.ToString();
                lbl_Q.Text = questions[id].question;
                radio_A.Text = questions[id].answer[0];
                radio_B.Text = questions[id].answer[1];
                radio_C.Text = questions[id].answer[2];
                radio_D.Text = questions[id].answer[3];
                //If-i sees on vastusevariantide värvimine - Radiobutton Array lahendusega tuleb parandada
                if (testEnded == true)
                {
                    radio_A.ForeColor = Color.Black;
                    radio_B.ForeColor = Color.Black;
                    radio_C.ForeColor = Color.Black;
                    radio_D.ForeColor = Color.Black;
                    switch (questions[id].correct)
                    {
                        case 1: radio_A.ForeColor = Color.Green;
                                break;
                        case 2: radio_B.ForeColor = Color.Green;
                                break;
                        case 3: radio_C.ForeColor = Color.Green;
                                break;
                        case 4: radio_D.ForeColor = Color.Green;
                                break;
                    }
                    if (questions[id].chosenAns != questions[id].correct)
                    {
                        switch (questions[id].chosenAns)
                        {
                            case 1: radio_A.ForeColor = Color.Red;
                                break;
                            case 2: radio_B.ForeColor = Color.Red;
                                break;
                            case 3: radio_C.ForeColor = Color.Red;
                                break;
                            case 4: radio_D.ForeColor = Color.Red;
                                break;
                        }
                    }
                }
                switch (questions[id].chosenAns)
                {
                    case 1: radio_A.Checked = true; break;
                    case 2: radio_B.Checked = true; break;
                    case 3: radio_C.Checked = true; break;
                    case 4: radio_D.Checked = true; break;
                    default:break;
                }
            }
            catch (System.IndexOutOfRangeException)
            {}
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            testTimer = new Timer.Timer(1000);
            testTimer.Elapsed += new System.Timers.ElapsedEventHandler(testTimer_Tick);
        }

        //Testi taimer
        void testTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime time = DateTime.Parse(endTime).Subtract(TimeSpan.Parse(DateTime.Now.ToLongTimeString()));
            lbl_timeLeft.Text = "Aega on: " + time.ToLongTimeString();
            if (time.Hour == 0 && time.Minute == 5 && time.Second == 0)
            {
                MessageBox.Show("Sul on veel 5 minutit jäänud!", "Tee ruttu!");
            }
            if (time.Hour == 0 && time.Minute == 0 && time.Second == 0)
            {
                Application.Exit();
            }

        }
        
        //Testi algus
        private void btn_start_Click(object sender, EventArgs e)
        {
            if (txt_Name.Text == "" || list_Class.SelectedItem == null)
            {
                MessageBox.Show("Täida väljad!", "Viga",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
            else
            {
                //Laeb küsimused struktuurist
                questions = Questions.Shuffle(questions);
                gui_questions = new TreeNode[questions.Length];
                for (int i = 0; i < questions.Length; i++)
                {
                    gui_questions[i] = new TreeNode("Küsimus nr " + (i + 1).ToString());
                    gui_questions[i].Tag = questions[i].ID;
                }
                list_Q.Nodes.AddRange(gui_questions);
                lbl_Progress.Text = "Nr: " + (currentID + 1).ToString() + "/" + questions.Length.ToString();
                LoadQuestion(currentID);
                studentName = txt_Name.Text;
                this.Text += " - " + studentName;

                //GUI muutus
                panel_start.Visible = false;
                btn_Confirm.Visible = true;
                panel_test.Visible = true;
                lbl_Progress.Visible = true;
            }
        }

        //Ühendatakse serveriga        
        private void btn_Connect_Click(object sender, EventArgs e)
        {
            try
            {
                server_Url = txt_Url.Text;
                reader = new XmlTextReader("http://" + server_Url + "/do.php?act=init");
                reader.WhitespaceHandling = WhitespaceHandling.None;
                XmlDocument xd = new XmlDocument();
                xd.Load(reader);
                if (xd.DocumentElement.InnerText != "inactive")
                {
                    testName = xd.SelectSingleNode("/test/name").InnerText;
                    startTime = xd.SelectSingleNode("/test/starttime").InnerText;
                    endTime = xd.SelectSingleNode("/test/endtime").InnerText;
                    XmlNodeList xml_questions = xd.SelectNodes("/test/selectedquestions/q");
                    questions = new Questions.Question[xml_questions.Count];
                    for (int i = 0; i < xml_questions.Count; i++)
                    {
                        questions[i].ID = xml_questions[i].SelectSingleNode("id").InnerText;
                        questions[i].question = xml_questions[i].SelectSingleNode("question").InnerText;
                        questions[i].answer = new string[4];
                        questions[i].answer[0] = xml_questions[i].SelectSingleNode("answer1").InnerText;
                        questions[i].answer[1] = xml_questions[i].SelectSingleNode("answer2").InnerText;
                        questions[i].answer[2] = xml_questions[i].SelectSingleNode("answer3").InnerText;
                        questions[i].answer[3] = xml_questions[i].SelectSingleNode("answer4").InnerText;
                        questions[i].correct = Convert.ToInt32(xml_questions[i].SelectSingleNode("correct").InnerText);
                        questions[i].picUrl = xml_questions[i].SelectSingleNode("picURL").InnerText;                        
                    }
                    this.Text = testName;
                    testTimer.Start();
                }
                else
                {
                    MessageBox.Show("Test pole aktiivne, väljun", "Teade", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    Application.Exit();
                }
                //GUI muutus
                panel_login.Visible = false;
                lbl_timeLeft.Visible = true;
                panel_start.Visible = true;
                txt_Name.Focus();
            }
            catch(System.Net.WebException n)
            {
                MessageBox.Show(n.Message);     
            }
        }

        //Testi lõpp
        private void EndTest()
        {
            testEnded = true;
            radio_A.AutoCheck = false;
            radio_B.AutoCheck = false;
            radio_C.AutoCheck = false;
            radio_D.AutoCheck = false;
            int points = 0;
            double score = 0;
            for (int i = 0; i < questions.Length; i++)
            {
                if (questions[i].chosenAns == questions[i].correct)
                {
                    points++;
                    gui_questions[i].ForeColor = Color.Green;
                }
                else
                {
                    gui_questions[i].ForeColor = Color.Red;
                }
            }
            float pointsperquestion = (float)questions.Length / (float)10;
            score = Math.Round(points / pointsperquestion,0,MidpointRounding.AwayFromZero);
            string response = NetFunc.HttpPost("http://" + server_Url + "/do.php?act=end", "name=" + studentName + "&class=" + list_Class.SelectedItem.ToString() + "&score=" + score.ToString());
            lbl_timeLeft.Visible = false;
            btn_Confirm.Enabled = false;
            testTimer.Stop();
            MessageBox.Show("Nimi: " + studentName + "\nPunkte: " + points.ToString() + " / " + questions.Length + "\n Hinne: " + score, "Tulemus",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }

        #region Graafilise liidese funktsioonid
        private void btn_Next_Click(object sender, EventArgs e)
        {
            if (currentID < questions.Length-1)
            {
                radio_A.Checked = false;
                radio_B.Checked = false;
                radio_C.Checked = false;
                radio_D.Checked = false;
                currentID++;
                LoadQuestion(currentID);
            }
            if (currentID + 1 == questions.Length)
            {
                btn_Next.Enabled = false;
            }
            btn_Back.Enabled = true;
        }

        private void btn_Back_Click(object sender, EventArgs e)
        {
            if (currentID > 0)
            {
                radio_A.Checked = false;
                radio_B.Checked = false;
                radio_C.Checked = false;
                radio_D.Checked = false;
                currentID--;
                LoadQuestion(currentID);
            }
            if (currentID == 0)
            {
                btn_Back.Enabled = false;
            }
            btn_Next.Enabled = true;
        }

        private void btn_Confirm_Click(object sender, EventArgs e)
        {
            EndTest();
        }


        private void list_Q_NodeMouseClick(object sender, System.Windows.Forms.TreeNodeMouseClickEventArgs e)
        {
            radio_A.Checked = false;
            radio_B.Checked = false;
            radio_C.Checked = false;
            radio_D.Checked = false;
            currentID = e.Node.Index;
            LoadQuestion(currentID);
            if (currentID == 0)
            {
                btn_Back.Enabled = false;
            }
            else
            {
                btn_Back.Enabled = true;
            }
            if (currentID + 1 == questions.Length)
            {
                btn_Next.Enabled = false;
            }
            else
            {
                btn_Next.Enabled = true;
            }
        }
    #region Radio nuppude valiku funktsioonid 
        private void radio_A_CheckedChanged(object sender, EventArgs e)
        {
            questions[currentID].chosenAns = 1;
            CompletedQ();
        }

        private void radio_B_CheckedChanged(object sender, EventArgs e)
        {
            questions[currentID].chosenAns = 2;
            CompletedQ();
        }

        private void radio_C_CheckedChanged(object sender, EventArgs e)
        {
            questions[currentID].chosenAns = 3;
            CompletedQ();
        }

        private void radio_D_CheckedChanged(object sender, EventArgs e)
        {
            questions[currentID].chosenAns = 4;
            CompletedQ();    
        }
        private void CompletedQ()
        {
            if (testEnded == false)
            {
                list_Q.Nodes[currentID].ForeColor = Color.Blue;
            }
            string missingQuestions = "";
            int i = 0;
            while (i < questions.Length)
            {
                if (questions[i].chosenAns == 0)
                {
                    missingQuestions += (i + 1).ToString() + ";";
                }
                i++;
            }
            if (missingQuestions == "" && testEnded == false)
            {
                btn_Confirm.Enabled = true;
            }
        }
        #endregion
    #endregion
    }
}